/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.task;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import org.chacha.dao.LoginTokenDAO;
import org.chacha.log.LogPrn;
import org.chacha.model.LoginToken;

/**
 * 
 *	@author: hejing
 *	@date: 2012-12-17-下午04:35:00
 */
public class TokenCleanTask {
	private long HOUR=3600*1000 ;	//MS
	Timer timer;
	private int pageNum=10000;
	private LogPrn log=new LogPrn(TokenCleanTask.class);
	
	public TokenCleanTask() {
		timer=new Timer();
	}
	
	public void startUp(){
		TimerTask task=new TokenTask();
		timer.schedule(task, 10, HOUR);
	}
	
	private class TokenTask extends TimerTask{

		@Override
		public void run() {
			try{
				LoginTokenDAO tokenDAO=new LoginTokenDAO();
				String lastID="-1";
				LinkedList<LoginToken> page=tokenDAO.getPage(pageNum, lastID);//首页
				while(!page.isEmpty()){
					for(LoginToken token:page){
						if(token.getTokenLifeTime()<System.currentTimeMillis()){
							tokenDAO.delete(token);
						}
						lastID=token.get_id();	
					}
					page=tokenDAO.getPage(pageNum, lastID);
				}
			}catch(Exception e){
				log.error("TokenTask exception:",e);
			}
		}
		
	}
}
